package cn.chaos.bio01;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;


/**
 * 
 * 1. 创建一个 Socket 实例，构造函数向指定的主机和端口建立一个 TCP 连接。
 * 2. 通过 Socket 的输入输出流进行通信。
 * 3. 使用 Socket 的 close 方法关闭连接。
 * 
 * @author E470OKL
 *
 */
public class TCPEchoClient {
    
    public static void main(String[] args) {
        String server = "localhost";
        int port = 11111;
        
        
        byte[] data = "hello 程超  Connected to server ... sending".getBytes(StandardCharsets.UTF_8);
        
        try (Socket socket = new Socket(server, port);) {

            System.out.println("Connected to server ... sending echo string.");
            
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            
            // 发送数据
            out.write(data);
            
            int totalBytesRcvd = 0; 
            int bytesRcvd;
            
            while (totalBytesRcvd < data.length ) {
                if ((bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) {
                    throw new SocketException("Connection closed prematurely");
                }
                totalBytesRcvd += bytesRcvd;
            }
            
            System.out.println("Received: "+ new String(data));
        } catch (UnknownHostException e ) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
            
        
        
        System.out.println("-- end --");
    }
    
}
